package com.example.gymlearning.service.impl;

import com.example.gymlearning.dto.request.LoginRequest;
import com.example.gymlearning.dto.request.RegisterRequest;
import com.example.gymlearning.dto.response.UserResponse;
import com.example.gymlearning.entity.User;
import com.example.gymlearning.mapper.UserMapper;
import com.example.gymlearning.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service

public class UserServiceImpl implements UserService {




    @Autowired
    private UserMapper usermapper;


    //注册功能
    @Override
    @Transactional
    public UserResponse register(RegisterRequest Request) {
        //检查用户名和邮箱
        if(isUserNameExist(Request.getUsername())){
            throw new RuntimeException("用户名已存在");
        }
//        if(isEmailExist(Request.getEmail())){
//            throw new RuntimeException("邮箱已被占用");
//        }
        //创建用户对象

        User user = createUserFromRequest(Request);


        //保存用户
        usermapper.insertUser(user);

       //转换响应DTO（不包含密码）
      return   convertToUserResponse(user);

    }


    //转换相应DTO的方法
    private UserResponse convertToUserResponse(User user) {
        return UserResponse.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .age(user.getAge())
                .experience(user.getExperience())
                .level(user.getLevel())
                .createTime(user.getCreateTime())
                .updatedTime(user.getUpdatedTime())
                .build();
    }

    //从请求中创建用户对象
    private  User createUserFromRequest(RegisterRequest Request){
        User user = new User();
        user.setUsername(Request.getUsername());
//        user.setEmail(Request.getEmail());
        user.setPassword(Request.getPassword());
//        user.setAge(Request.getAge());
        user.setExperience(0);      // 默认经验值
        user.setLevel(1);           // 默认等级
        user.setCreateTime(new Date());
        user.setUpdatedTime(new Date());
        return user;

    }

    @Override
    public boolean isUserNameExist(String username) {
        return usermapper.selectUserByName(username) != null;
    }

    @Override
    public boolean isEmailExist(String email) {
        return usermapper.findByEmail(email) != null;
    }

    @Override
    public UserResponse login(LoginRequest loginRequest) {
        //根据用户名查找用户
        User user = usermapper.selectUserByName(loginRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        //验证密码
        if(!validatePassword(loginRequest.getPassword(), user.getPassword())){
            throw new RuntimeException("密码错误");
        }
        //更新最后的登录时间
        user.setUpdatedTime(new Date());
        usermapper.updateUser(user);
        //返回用户信息，不包含密码
        return  convertToUserResponse(user);
    }



    @Override
    public boolean validatePassword(String rawPassword, String encodedPassword) {
        return rawPassword.equals(encodedPassword);
    }

    @Override
    public UserResponse getUserById(int id) {
        User userById = usermapper.getUserById(id);
        return userById != null ? convertToUserResponse(userById) : null;
    }

    @Override
    public UserResponse getUserByUsername(String username) {
        User user = usermapper.selectUserByName(username);
        return  user!= null ? convertToUserResponse(user) : null;
    }

    @Override
    public List<UserResponse> getAllUsers() {
        List<User> users = usermapper.getAllUser();
        //将实体列表转换成响应对象列表
        return users.stream()
                .map(this::convertToUserResponse)
                .collect(Collectors.toList());

    }
}
